<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model:model-value="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  inject,
  watchEffect,
  computed,
} from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import {
  IDomEditor,
  IToolbarConfig,
  IEditorConfig,
  DomEditor,
} from '@wangeditor/editor';
import { useInjectDisabled } from 'ant-design-vue/es/config-provider/DisabledContext';
import type { _EditorProps } from '../interface';
import { message } from 'ant-design-vue';

const props = defineProps<_EditorProps>();

const html = defineModel<string>('value');

const disabled = useInjectDisabled();
const mode = 'default';

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<IDomEditor>();

const toolbarConfig = computed<Partial<IToolbarConfig>>(() => {
  const result: Partial<IToolbarConfig> = {};
  if (props.toolbarKeys?.length) {
    result['toolbarKeys'] = props.toolbarKeys;
  }
  if (props.excludeKeys?.length) {
    result['excludeKeys'] = props.excludeKeys;
  }
  return result;
});
const editorConfig: IEditorConfig = {
  placeholder: '请输入内容...',
  customAlert: (s: string, t: string) => {
    // TS 语法
    // editorConfig.customAlert = (s, t) => {                 // JS 语法
    switch (t) {
      case 'success':
        message.success(s);
        break;
      case 'info':
        message.info(s);
        break;
      case 'warning':
        message.warning(s);
        break;
      case 'error':
        message.error(s);
        break;
      default:
        message.info(s);
        break;
    }
  },
  scroll: false,
  readOnly: false,
  autoFocus: false,
  MENU_CONF: {
    uploadImage: {
      async customUpload(
        file: File,
        insertFn: (arg0: any, arg1: any, arg2: any) => void,
      ) {
        if (props.uploadImage) {
          const result = await props.uploadImage?.(file);
          if (result.status === false) return;
          insertFn(result?.url, result?.alt, result?.href);
        }
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  const toolbar = DomEditor.getToolbar(editor);
  console.log(toolbar?.getConfig().toolbarKeys);
};

watchEffect(() => {
  if (disabled.value) {
    editorRef.value?.disable();
  } else {
    editorRef.value?.enable();
  }
});
</script>
